package tribe.vilt.lost.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import tribe.vilt.lost.activity.HomeActivity;
import tribe.vilt.lost.util.C2DMessaging;
import tribe.vilt.lost.util.Constants;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Created by Tobias Ericsson
 */
public class C2DMService extends IntentService {

    private final static String TAG = C2DMService.class.getSimpleName();

    public C2DMService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent " + intent.getAction());

        boolean registered;

        final SharedPreferences prefs = getApplicationContext().getSharedPreferences(
                C2DMessaging.SHARED_PREFS,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        if (Constants.REGISTER.equals(intent.getAction())) {
            editor.putString("registration_id",intent.getStringExtra("registration_id"));
            editor.commit();
            registered = registerOnLostServer();
        } else {
            registered = !unRegisterOnLostServer();
        }


        editor.putBoolean("registered", registered);
        editor.commit();

        Intent callbackIntent = new Intent(getApplicationContext(), HomeActivity.class);
        callbackIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(callbackIntent);
    }

    private boolean toggleRegisteredOnLostServer(boolean register) {
        SharedPreferences sharedPreferences = getSharedPreferences("lost", 0);

        String gmail = sharedPreferences.getString("gmail", null);
        String registrationId = sharedPreferences.getString("registration_id", null);

        URL url = null;
        try {
            url = new URL("http://vaffododo.appspot.com/register");

            HttpURLConnection connection = null;

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String idPart = "registration_id=" + registrationId;
            String mailPart = "gmail=" + gmail;
            String regPart = "register=" + register;
            String postBody = regPart + "&" + mailPart + "&" + idPart;

            writer.write(postBody);
            writer.close();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                Log.d(TAG, "OK");
                return true;
            } else {
                Log.d(TAG, "FAILED" + connection.getResponseCode());
            }

        } catch (ProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return false;
    }

    private boolean unRegisterOnLostServer() {
        Log.d(TAG, "unRegisterOnLostServer");
        return toggleRegisteredOnLostServer(false);
    }

    private boolean registerOnLostServer() {
        Log.d(TAG, "registerOnLostServer");
        return toggleRegisteredOnLostServer(true);
    }
}
